<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Facades\JWTAuth;

class ApiAuth
{

    public function handle($request, Closure $next,$role=null)
    {
        if($role){
            try{
                auth()->shouldUse($role);  //这里设置是用auth.php文件中配置的哪个guard
                $token=$request->header('Authorization');
                if(config('app.debug') && is_numeric($token)){
                    auth()->setToken(auth()->tokenById($token));
                    return $next($request);
                }
                $token_role = JWTAuth::parseToken()->getClaim('role');
                if ($token_role && $token_role == $role) {
                    return $next($request);
                }
            }catch (\Exception $e){
                abort(401,$e->getMessage());
            }

        }

        abort(401,'无效的用户token');
    }
}
